/*******************************************************************************
 *
 * Copyright (c) 2008-2011 ayound@gmail.com, guwei8576431@gmail.com
 * This program and the accompanying materials
 * are made available under the terms of the GNU GENERAL PUBLIC LICENSE 
 * which accompanies this distribution, and is available at
 * http://dev.perl.org/licenses/gpl1.html
 * All rights reserved.
 * 
 * Created on 2009-10-18
 *******************************************************************************/

package org.cgtw.scriptprofile.server;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;

import org.cgtw.scriptprofile.engine.compile.IScriptCompileEngine;
import org.cgtw.scriptprofile.engine.manager.ScriptCompileManager;
import org.cgtw.scriptprofile.server.model.ProfileSourceInfo;

public class ScriptProfileServer {
	private ServerSocket serverSocket;

	private boolean running = false;
	
	private int port;

	private URL remoteUrl;

	private IScriptCompileEngine compileEngine;

	private String encoding;

	
	public ScriptProfileServer(ProfileSourceInfo info, ServerSocket socket){
		serverSocket = socket;
		port = socket.getLocalPort();
		try {
			String url = info.getUrl();
			if (url.startsWith("http") || url.startsWith("file")) {
				remoteUrl = new URL(url.replace(":///", "://"));
			} else {
				remoteUrl = new URL("file://" + url);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		start();
	}
	
	public void start(){
		compileEngine = ScriptCompileManager.getInstance().getScriptCompileEngine();
		running = true;
		new ScriptConnectThread().start();
	}
	
	public void stop(){
		running = false;
		try {
			if(serverSocket!=null){
				serverSocket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String getLocalBaseUrl(){
		return "http://localhost:" + port + "";
	}
	
	public URL getRemoteBaseUrl(){
		return remoteUrl;
	}
	
	private class ScriptConnectThread extends Thread{

		/* (non-Javadoc)
		 * @see java.lang.Thread#run()
		 */
		@Override
		public void run() {
			while (ScriptProfileServer.this.running) {
				if (!ScriptProfileServer.this.serverSocket.isClosed()) {
					Socket conn = null;
					try {
						conn = ScriptProfileServer.this.serverSocket.accept();
					} catch (IOException e) {
						
					}
					new ScriptRemoteConnectThread(conn).start();
				}
			}
		}
		
	}

	/**
	 * @return Returns the encoding.
	 */
	public String getEncoding() {
		return encoding;
	}

	/**
	 * @param encoding The encoding to set.
	 */
	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	/**
	 * @return Returns the compileEngine.
	 */
	public IScriptCompileEngine getCompileEngine() {
		return compileEngine;
	}

}
